/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
import moment from 'moment'
// 引入antd的组件
import {
  Form,
  Row,
  Col,
  Input,
  Cascader,
  Tag,
  DatePicker,
  Select,
  Button,
  Modal,
  Divider,
  Tooltip,
  Icon,
  message,
  Radio,
  Switch,
  Table,
  Popconfirm,
  Transfer,
} from 'antd'
const { Search } = Input;
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import { isEmpty, isArray, cloneDeep, chunk, set } from 'lodash'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reg } from 'utils/util'
// 当前组件样式
import styles from './intermediaryDetailStyle.less'
import Img from 'widget/ImgBoost/ImgBoost'

import ListPage from 'widget/PageTmpl/ListPage'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import PopUpSelect from 'widget/PopUpSelect/PopUpSelect'
import Track from 'widget/Map/Track'
import { Grid, QueryCondition } from 'widget/Grid/index'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

const FormItem = Form.Item
const { TextArea } = Input
const InputGroup = Input.Group;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;
const { Option } = Select;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 15 },
}
const formItemLayout01 = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
}
const formItemLayout02 = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
}
const formItemLayout03 = {
  labelCol: { span: 9 },
  wrapperCol: { span: 14 },
}
const formItemLayout04 = {
  labelCol: { span: 12 },
  wrapperCol: { span: 11 },
}
const formItemLayout05 = {
  labelCol: { span: 7 },
  wrapperCol: { span: 12 },
}


/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const routeView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFieldsAndScroll, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { productList,selectedKey,selectedTeams,teamsModalObj,biz1,nameModalObj,pageType, id, modalObj, formData, allAreaList, callModal, callModalTitle, tableData, pageConfig, loading, onItem, selectedRowKeys, timeModalObj, visitTime, marketingAction } = modelObj
  // modelObj.xxx获取model中状态机的值
  // console.log('routeView', modelObj,visitTime)
  tableData.dataSource.map((item) => {
    item.key = item.productId
    item['teamNames']
  })

  let pageProps = {   //中介公司名称
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `3rd/commission/queryMecSystemVendersVl`,
      // 接口方式
      method: 'POST',
      headers: {
        'Content-type': 'application/json'
      },
      app: '',
      // 接口参数
      params: {
        "pageSize":10,
        "pageNo":1,
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,

      selectedRowKeys:'',
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'vendor_NAME',
            zh_name: '中介公司名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
        ],
        searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', e)
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table':
        {
          rowSelectionInfo: {
            type: 'radio',
          },
          status_params: 'status=0',
          status_text: '全部',
          // 表头字段列表
          scroll: {x: 1000},
          fields: [
            {
              en_name: 'vendor_NAME',
              zh_name: '中介公司名称',
            },
            // {
            //   en_name: 'jgzz_FISCAL_CODE',
            //   zh_name: '企业性质',
            // },
            {
              en_name: 'corp_REPRE',
              zh_name: '法人',
            },
            {
              en_name: 'incompany_CATEGORY_DSC',
              zh_name: '供应商类型',
            },
            {
              en_name: 'fms_VENDOR_NUM',
              zh_name: '往来段编码',
            },
            {
              en_name: 'incompany_CODE',
              zh_name: '供应商代码',
            },
            {
              en_name: 'jgzz_FISCAL_CODE',
              zh_name: '统一社会信用代码',
            },
          ],
          // 表格操作
          actions: [],
        },
      action_bar: [
        {
          // label:'',
          // type:'',
          rowSelection: [],
          render: () => {
            return <Input hidden/>
          },
          onClick: (e, row) => {
          }
        },
      ]
    },
  }

  // 表格配置------------开始
  // 序号  秒杀商品 商品类型 秒杀时间 原价 秒杀价 应付报名费  应付定金
  // 序号  秒杀商品 name  商品类型 productType  秒杀时间 startTime endTime   原价 originalPrice  秒杀价 seckillPrice 应付报名费 securityMoney  应付定金  earnestMoney
  const teamsColumns = [
    {
      title: '团队名称',
      dataIndex: 'teamName',
    },
    {
      title: '管理员姓名',
      dataIndex: 'adminName',
    },
    {
      title: '预留电话',
      dataIndex: 'preMobile',
    },
  ];
  const teamsRowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedTeams = selectedRows
    }
  };
  const columns1 = [
    {
      title: '楼盘名称', dataIndex: 'name', key: 'name', width: 200,
      render: function (value, item, index) {
        return item.productName || item.name || ''
      }
    },
    {
      title: '合同有效期', dataIndex: 'date', key: 'date',
      render: function (value, item, index) {
        let idx = pageConfig.pageSize * (pageConfig.pageNo - 1) + index
        let { startDate = null, endDate = null, date = null } = item
        if (!date && (startDate || endDate)) {
          item.date = [startDate, endDate]
        }
        return <div style={{ width: '400px' }}>
          <FormItem>
            {getFieldDecorator('table_item_' + item.productId, {
              initialValue: item.date && [moment(item.date[0]), moment(item.date[1])] || null,
              rules: [
                { required: true, message: '请输入合作合同有效期', },
              ],
            })(<RangePicker
              required={true}
              placeholder={['开始时间', '结束时间']}
              allowClear={false}
              // value={item.date&&[moment(item.date[0]),moment(item.date[1])]||null}
              format="YYYY-MM-DD"
              onChange={(dates, dateStrings) => {
                item.date = dateStrings;
                // tableData.dataSource.map((item_s)=>{
                //   if(item.productId==item_s.productId){
                //     item_s.date=dateStrings
                //   }
                // })
                set(tableData.dataSource, '[' + idx + '].date', dateStrings)
                changeState({ tableData })
              }} />)}

            {/*<span style={{width: '40%'}} className="mgl1">到期后中介将不能登录</span>*/}
          </FormItem>
        </div>

      }
    },
  ]
  const columns2 = [
    {
      title: '楼盘名称', dataIndex: 'name', key: 'name', width: 180,
      render: function (value, item, index) {
        return item.productName || item.name || ''
      }
    },
    {
      title: '合同有效期', dataIndex: 'date', key: 'date', width: 350,
      render: function (value, item, index) {
        let idx = pageConfig.pageSize * (pageConfig.pageNo - 1) + index
        let { startDate = null, endDate = null, date = null } = item
        if (!date && (startDate || endDate)) {
          item.date = [startDate, endDate]
        }
        return <div>
          <FormItem>
            {getFieldDecorator('table_item_' + item.productId, {
              initialValue: item.date && [moment(item.date[0]), moment(item.date[1])] || null,
              rules: [
                { required: true, message: '请输入合作合同有效期', },
              ],
            })(<RangePicker
              required={true}
              placeholder={['开始时间', '结束时间']}
              disabled={productList.includes(item.productId)||localStorage.getItem('username')=='admin'?false:true}
              allowClear={false}
              // value={item.date&&[moment(item.date[0]),moment(item.date[1])]||null}
              format="YYYY-MM-DD"
              onChange={(dates, dateStrings) => {
                item.date = dateStrings;
                // tableData.dataSource.map((item_s)=>{
                //   if(item.productId==item_s.productId){
                //     item_s.date=dateStrings
                //   }
                // })
                set(tableData.dataSource, '[' + idx + '].date', dateStrings)
                changeState({ tableData })
              }} />)}

            {/*<span style={{width: '40%'}} className="mgl1">到期后中介将不能登录</span>*/}
          </FormItem>
        </div>

      }
    },
    {
      title: '报备到访最短有效时间（默认与楼盘所设定时间保持一致，请谨慎更改）', dataIndex: 'visitMinHours', key: 'visitMinHours', width: 400,
      render: function (value, item, index) {
        let idx = pageConfig.pageSize * (pageConfig.pageNo - 1) + index
        let { visitMinHours, disabled } = item
        // if (!visitMinHours) {
        //   set(tableData.dataSource, '[' + idx + '].visitMinHours', '2')
        //   changeState({ tableData })
        // }
        let min = (visitMinHours * 60).toFixed(2)
        // console.log(min)
        var mt8 = { marginTop: '8px' }
        var mt14 = { marginTop: '14px' }
        return <div style={{ width: '400px' }} >
          <Row>
            <Col span={20}>
              <FormItem>
                {getFieldDecorator('visitMinHours' + index, {
                  initialValue: visitMinHours,
                  rules: [
                    { pattern: /^\d{0,8}\.{0,1}(\d{1,2})?$/, message: '请输入数字或两位小数' }
                  ],
                })(
                  <Input
                    rows={4}
                    placeholder={'请输入报备到访最短有效时间'}
                    addonAfter={<label>
                      {/* <Tooltip title="编辑"><Icon className={cx('editIcon')} type="edit" onClick={() => {
                      set(tableData.dataSource, '[' + idx + '].disabled', !disabled)
                      changeState({ tableData })
                    }} /></Tooltip> */}
                    <span>小时</span></label>}
                    disabled={(productList.includes(item.productId)||localStorage.getItem('username')=='admin')&&visitTime?false:true}
                    // disabled={disabled}
                    onChange={(e) => {
                      console.log(e.target.value)
                      item.visitMinHours = e.target.value;
                      set(tableData.dataSource, '[' + idx + '].visitMinHours', e.target.value)
                      changeState({ tableData })
                    }}
                    onBlur={() => {
                      // set(tableData.dataSource, '[' + idx + '].disabled', true)
                      changeState({ tableData })
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={2} style={mt8}>
              <Tooltip title="作为扫码判客的提示，必须要在报备时间+到访最短有效时间  后 且在合同有效期内 到访才有效。支持小数点后2位。"><Icon type="question-circle" style={{ fontSize: '16px', color: '#08c', marginLeft: '8px', marginTop: '8px' }} /></Tooltip>
            </Col>
            {/* <Col span={10} style={mt14}><span style={{ fontSize: '14px', color: '#08c' }} >等于{min}分钟</span></Col> */}
          </Row>

        </div>
      }
    },
    {
      title: '团队名称', dataIndex: 'teamNames', key: 'teamNames', width: 200,
      render: function (value, item, index) {
        if(item.teamNames){
          return  <div className={cx('flex')}>
                      <span  className={cx('span_overflow_omit')}>{item.teamNames}</span>
                      <span style={{display:productList.includes(item.productId)||localStorage.getItem('username')=='admin'?'block':'none'}} className={cx('red_del_style')} onClick={() => { delTeams(value,item,index) }}>X</span>
                </div>
        }else{
          return <Button  onClick={() => { upTeams(value,item,index) }}  type="link">选择</Button>
        }
      }
    },
  ]
  // let columns = visitTime ? columns2 : columns1
  let columns = columns2
  const gridProps = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange',
    data: {
      // columns: [].concat(columns, generateAction()),//已发布的活动不能添加和删除时间段
      columns: columns
      ,//已发布的活动不能添加和删除时间段
      pageConfig, tableData, selectedRowKeys,
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      tableData = { ...tableData, pageNo, pageSize }
      pageConfig = { ...pageConfig, pageNo, pageSize }
      changeState({ tableData, pageConfig });
    },
    scroll: { x: 1000 },
    loading
  }
  // 点击处理事件
  const modalGridProps = {
    nameSpace: namespace,
    selectedKeysChange: 'selectedKeysChange',
    data: {
      columns: [{ title: '秒杀商品', dataIndex: 'name', key: 'name' },],
      pageConfig: modalObj.pageConfig,
      tableData: modalObj.tableData,

      lectedRowKeys: modalObj.selectedRowKeys,
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChangeModal`, payload: { pageNo, pageSize } });
    },
    scroll: { x: 1000 },
    loading
  }
  // 分发到model文件中effects的xxx方法
  // 表格操作区域
  function generateAction() {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (data, record, index) => {
        return (
          <span>
            <Popconfirm Collapse title={`确定要删除吗？`} okText='确定' cancelText='取消' onConfirm={() => deleteItem(record)}>
              <a href='javascript:void(0)' onClick={(e) => {
                // 阻止事件冒泡
                // e.stopPropagation();
              }}>删除
                  </a>
            </Popconfirm>
          </span>
        )
      }
    }
  }
  //解除时间关联
  function deleteItem(item = {}) {
    dispatch({
      type: `${namespace}/relieveTimeSlot`,
      payload: {
        ...item
      }
    })
  }
  // 更新商品状态 发布、撤销 发布状态	published（1，未发布。2，已发布，3已撤销）
  function updatePublished(newType) {
    dispatch({
      type: `${namespace}/updatePublished`,
      payload: {
        newType: newType
      }
    })
  }

  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ...payload }
    })
  }
  // 弹窗
  function inputChange(value, key = '', index) {
    if (key == 'district') {
      formData.district = value
      formData.houseList = []
      setFieldsValue({ 'houseList': '' })
      dispatch({ type: `${namespace}/getHouseList`, payload: { province: value[0], city: value[1] } })
    }
    if (key == 'coperationDate' && value.length == 2) {
      set(formData, 'businessInfo.startDate', value && value[0])
      set(formData, 'businessInfo.endDate', value && value[1])
    }
    set(formData, key, value)

    changeState({ formData })
  }
  function formItemChange(val, key, index) {
    console.log(val, key)
    let { teams } = formData
    if (val && teams[index].teamType) {
      delete teams[index].teamType
      set(formData, key, val)
    } else {
      set(formData, key, val)
    }

    changeState({ formData })
  }
  // 详情页跳转
  function routerGo({ type = '', }) {
    let urlArray = MODULE_TO_ROUTES[namespace].urlArray
    hashHistory.push({
      pathname: urlArray[0],
      query: {
        pageType: type,
        id: id,
      }
    })
  }
  //校验
  function validator(rule, value, callback, type = '') {

  }

  // updateProduct createProduct
  function save() {
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          // type: `${namespace}/${{ edit: 'update', add: 'create', detail: '' }[pageType]}`,
          type: `${namespace}/create`,
          payload: {}
        })
      }
      form.resetFields()
    })
  }
  // 弹出搜索中介名称弹窗
  function onSearchDialog(){
    if(formData.orgBasicInfo.channel == false){
      nameModalObj.visible = !nameModalObj.visible
    }
    changeState({ nameModalObj})
  }
  function confirmSearchDialog(){
    formData.orgBasicInfo.name = biz1.selectedRows[0].vendor_NAME
    formData.orgBasicInfo.legalMan = biz1.selectedRows[0].corp_REPRE
    formData.orgBasicInfo.orgCode = biz1.selectedRows[0].jgzz_FISCAL_CODE
    formData.orgBasicInfo.fmsVendorNum = biz1.selectedRows[0].fms_VENDOR_NUM
    formData.orgBasicInfo.incompanyCode = biz1.selectedRows[0].incompany_CODE
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {formData}
    })
    form.resetFields()
    onSearchDialog()
  }

  //选择团队弹窗
  function upTeams(value,item,index){
   
    if(formData.teams.length){
      for(var i=0;i<formData.teams.length;i++){
        formData.teams[i]['key'] = i
      }
    }
    if(item&&item.key){
      selectedKey = item.key
    }
    teamsModalObj.visible = !teamsModalObj.visible
    changeState({ teamsModalObj,selectedKey})
  }

  function confirmTeams(){
    let arr = []
    for(var item of selectedTeams){
      arr.push(item.teamName)
    }
    for(var itemd of tableData.dataSource){
      if(itemd.key == selectedKey){
        itemd['teamNames'] = arr.join(',')
      }
    }
    changeState({ tableData})
    upTeams()
  }
  //删除
  function delTeams(value,item,index){
    for(var itemd of tableData.dataSource){
      if(itemd.key == item.key){
        let teamNames = itemd.teamNames?itemd.teamNames.split(","):''
        for(var it of teamNames){
          for(var dd of formData.teams){
            if(it == dd.teamName){
              let arr = []
              if(dd.productList&&dd.productList.length){
                dd.productList.map((em, index) => {
                  if (itemd.productId != em.productId) {
                    arr.push(em)
                  }
                })
                dd.productList = arr
              }
            }
          }
        }
        itemd.teamNames =''
      }
    }
    changeState({ tableData,formData})
  }

  // function updateModal () {
  //   modalObj.visible=!modalObj.visible
  //   changeState({modalObj})
  // }

  function changeDate(queryList) {
    let date = queryList[0].value
    changeState({ date })
    console.log('changeDate', queryList)
  }

  function confirmCbk(onItem = []) {
    // e.preventDefault(e);
    modalObj.visible = false
    onItem.map((item) => {
      item.key = item.productId
      item.projectName = item.name
    })

    tableData.dataSource = onItem
    tableData.total = tableData.dataSource.length
    changeState({ tableData, onItem: [], modalObj })
  }

  // 弹窗
  function updateModal() {
    modalObj.visible = !modalObj.visible
    // if(modalObj.visible){
    //   resetFields(['newTime'])
    //   formData.newTime=null
    //   // onItem=[]
    // }
    if (modalObj.visible) {
      modalObj.queryList[0] = { ...modalObj.queryList[0], pageNo: 1, value: [] }
      onItem = tableData.dataSource || []
      // onItem=[]
    }
    changeState({ modalObj, onItem })
  }
  // 弹窗 table_item_1059652543220838400
  function updateTimeModal(flag = false) {
    let fileName = ''
    timeModalObj.visible = !timeModalObj.visible
    if (timeModalObj.visible) {
      resetFields(['newTime'])
      formData.newTime = null
      // onItem=[]
    } else if (flag) {
      tableData.dataSource.map((item) => {
        if (selectedRowKeys.indexOf(item.productId + '') > -1) {
          item.date = formData.newTime
          fileName = 'table_item_' + item.productId
          setFieldsValue({
            [fileName]: item.date && [moment(item.date[0]), moment(item.date[1])] || null
          })
        }
      })
    }
    changeState({ timeModalObj, formData, tableData })
  }
  //批量删除选中项
  function deleteItems() {
    let arr = []
    tableData.dataSource.map((item, index) => {
      if (selectedRowKeys.indexOf(item.productId + '') == -1) {
        arr.push(item)
      }
    })
    tableData.dataSource = arr
    tableData.total = tableData.dataSource.length
    changeState({ tableData })
  }
  //添加团队
  function add(idx) {
    let teamsObj = { isCooperation: true }
    let arr = formData.teams
    // console.log(arr)
    formData.teams.push(teamsObj)
    set(formData, 'teams', arr)
    changeState(formData)
  }
  //移除团队
  function remove(idx) {
    set(formData, 'teams', formData.teams.filter((key, index) => index !== idx))
    changeState(formData)
    form.resetFields([`adminName[${idx}]`, `preMobile[${idx}]`, `teamName[${idx}]`])
  }
  const formItems = formData.teams.map((item, idx) => {
    return (
      <Row key={idx}>
        <Row>
          <Col className="col" span={6}>
            <FormItem {...formItemLayout03}
              label={idx == 0 ? "默认团队名称" : '团队名称'}>

              {getFieldDecorator(`teamName[${idx}]`, {
                initialValue: item.teamName ? item.teamName : undefined,
                rules: [
                  { required: true, whitespace: true, message: '请输入团队名称' },
                ],
              })(<Input
                placeholder={'请输入团队名称'}
                onChange={(e) => { formItemChange(e.target.value, `teams[${idx}].teamName`, idx) }}
              />)}
            </FormItem>
          </Col>
          <Col className="col" span={5}>
            <FormItem {...formItemLayout03}
              label="管理员姓名">

              {getFieldDecorator(`adminName[${idx}]`, {
                initialValue: item.adminName ? item.adminName : undefined,
                rules: [
                  { required: true, whitespace: true, message: '请输入管理员姓名' },
                ],
              })(<Input
                placeholder={'请输入管理员姓名'}
                onChange={(e) => { formItemChange(e.target.value, `teams[${idx}].adminName`, idx) }}
              />)}
            </FormItem>
          </Col>
          <Col className="col" span={6}>
            <FormItem {...formItemLayout}
              label="预留手机号">
              {getFieldDecorator(`preMobile[${idx}]`, {
                initialValue: item.preMobile ? item.preMobile : undefined,
                rules: [{ required: true, whitespace: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ }]
              })(<Input
                placeholder={'请输入预留手机号'}
                onChange={(e) => { formItemChange(e.target.value, `teams[${idx}].preMobile`, idx) }}
              />)}

            </FormItem>
          </Col>

          <Col className="col" span={6}>
            <FormItem {...formItemLayout}
              label="合作码">
              {getFieldDecorator(`cooperationCode[${idx}]`, {
                initialValue: item.cooperationCode ? item.cooperationCode : undefined,
                rules: [{ required: false }]
              })(<Input disabled
                placeholder={''}
              />)}

            </FormItem>
          </Col>

          <Col className="col" span={1}>
            {formData && formData.teams.length > 1 && idx != 0 ? (
              <Popconfirm placement="topLeft" title={'是否确认删除该团队，删除后整个团队成员都无法登录'} onConfirm={() => remove(idx)} okText="确定" cancelText="取消">
                <Icon
                  className="dynamic-delete-button"
                  type="minus-circle-o"
                  disabled={formData && formData.teams.length === 1}
                />
              </Popconfirm>
            ) : null}
          </Col>
        </Row>
        {marketingAction &&
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout04}
                label="是否美的置业营销操盘">
                {getFieldDecorator(`isCooperation[${idx}]`, {
                  initialValue: item.isCooperation,
                  rules: [{ required: true }]
                })(<RadioGroup onChange={(e) => { formItemChange(e.target.value, `teams[${idx}].isCooperation`, idx) }}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>)}

              </FormItem>
            </Col>
            {!item.isCooperation &&
              <Col className="col" span={6}>
                <FormItem {...formItemLayout05}
                  label="团队类型">
                  {getFieldDecorator(`teamType[${idx}]`, {
                    initialValue: item.teamType,
                    rules: [{ required: true, message: '请选择团队类型' }]
                  })(<Select placeholder="请选择团队类型" onChange={(e) => { formItemChange(e, `teams[${idx}].teamType`, idx) }}>
                    <Option value={15}>合作方分销</Option>
                    <Option value={17}>合作方自拓</Option>
                    <Option value={18}>合作方全民营销</Option>
                  </Select>)}

                </FormItem>
              </Col>
            }
          </Row>
        }


      </Row>
    )
  })
  // adminInfo(name preMobile)   orgBasicInfo(name legalMan  orgCode addressCode detailAddress orgId ) businessInfo(startDate endDate  commissionRate visitValidTime recommendValidTime dealValidTime  agentConfigId )  houseList  state
  function updateCallModal(flag = false, type = 0) {
    changeState({ callModal: flag })
    if (type == 1) {
      dispatch({
        type: `${namespace}/create`,
        payload: {
          type,
        }
      })
    }
  }
  if (!!modelObj.biz1) {
    pageProps.biz = modelObj.biz1
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz1:biz }
      })
    }
  }
  return (
    <div className={cx('public_listMain')}>
      <div className="functionButton">
        <Button type='primary' loading={modelObj.btnLoading} onClick={() => { save() }}>保存</Button>
        {/*<Button type='primary' onClick={()=>{onCancel()}}>取消</Button>*/}
        {/*<Button type='primary' onClick={() => { }}>导出模板</Button>*/}
      </div>
      {/* <CollapsiblePanels title="中介公司禁用" hideUpDownBtn={true}>
        <Row>
          <Col className="col" span={12}>
            <FormItem {...formItemLayout}
              label="中介公司禁用">
              {getFieldDecorator('state', {
                initialValue: formData.state,
                rules: [
                  { required: true, message: '请输入中介公司名称' },
                ],
              })(<Switch checkedChildren="" unCheckedChildren="" checked={formData.state == 2} onChange={(checked) => inputChange(checked ? 2 : 1, 'state')} />
              )}
            </FormItem>
          </Col>
        </Row>
      </CollapsiblePanels> */}
      <CollapsiblePanels title="中介公司管理员登录信息" hideUpDownBtn={true}>
        {formItems}
        <Button type="dashed" onClick={() => add()} style={{ width: '60%' }}>
          <Icon type="plus" /> 新增团队
            </Button>
        {/* <Row>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
                      label="姓名">
            
              {getFieldDecorator('adminInfo.name', {
                initialValue: formData.adminInfo.name,
                rules: [
                  { required: true, whitespace: true, message: '请输入姓名' },
                ],
              })(<Input
                placeholder={'请输入姓名'}
                disabled={pageType=='edit'}
                onChange={(e) => { inputChange(e.target.value, 'adminInfo.name') }}
              />)} 
            </FormItem>
          </Col>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
                      label="预留手机号">
              {getFieldDecorator('adminInfo.preMobile', {
                initialValue: formData.adminInfo.preMobile,
                rules: [{ required: true,whitespace: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ }]
              })(<Input
                placeholder={'请输入预留手机号'}
                disabled={pageType=='edit'}
                onChange={(e) => { inputChange(e.target.value, 'adminInfo.preMobile') }}
              />)}
            </FormItem>
          </Col>
        </Row> */}
      </CollapsiblePanels>

      <CollapsiblePanels title="中介公司基本信息" hideUpDownBtn={true}>
      <Row>
        <Col className="col" span={6}>
              <FormItem {...formItemLayout04}
                label="是否自渠">
                {getFieldDecorator(`orgBasicInfo.channel`, {
                  initialValue: formData.orgBasicInfo.channel,
                  rules: [{ required: true ,message: '请选择自渠方式'}]
                })(<RadioGroup onChange={(e) => { inputChange(e.target.value, `orgBasicInfo.channel`) }}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>)}

              </FormItem>
            </Col>
        </Row>
        <Row>
          <Col className="col" span={8} style={{position: 'relative'}}>
            <FormItem {...formItemLayout}
              label="中介公司名称">
              {getFieldDecorator('orgBasicInfo.name', {
                initialValue: formData.orgBasicInfo.name,
                rules: [
                  { required: true, whitespace: true, message: '请输入中介公司名称' },
                ],
              })(
                <Input  disabled={formData.orgBasicInfo.channel == false}
                  placeholder={'请输入中介公司名称'}
                  onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.name') }}
                />
                // <Search disabled={formData.orgBasicInfo.channel == false}
                // placeholder="请输入中介公司名称"
                // onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.name') }}
                // onSearch={() => { onSearchDialog() }}
                // />
              )}
            </FormItem>
            <Button icon="search" style={{display:formData.orgBasicInfo.channel == false?'block':'none',position: "absolute",right:'-64px',top: '4px', cursor: "pointer",zIndex: 99}} type='primary' onClick={() => { onSearchDialog() }}>选择</Button>
          </Col>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="法人">
              {getFieldDecorator('orgBasicInfo.legalMan', {
                initialValue: formData.orgBasicInfo.legalMan,
                rules: [
                  { required: formData.orgBasicInfo.channel?true :false, whitespace: true, message: '请输入法人', },
                ],
              })(<Input
                placeholder={'请输入法人'} 
                onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.legalMan') }}
              />)}
            </FormItem>
          </Col>
        </Row>
        <Row style={{display: formData.orgBasicInfo.channel == false? 'block' : 'none'}}>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="往来段编码">
              {getFieldDecorator('orgBasicInfo.incompanyCode', {
                initialValue: formData.orgBasicInfo.incompanyCode,
                rules: [
                  { required: formData.orgBasicInfo.channel == false?true:false, whitespace: true, message: '请输入往来段编码' },
                ],
              })(
                <Input 
                  placeholder={'请输入往来段编码'} disabled={formData.orgBasicInfo.channel == false}
                  onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.incompanyCode') }}
                />
              )}
            </FormItem>
          </Col>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="供应商编码">
              {getFieldDecorator('orgBasicInfo.fmsVendorNum', {
                initialValue: formData.orgBasicInfo.fmsVendorNum,
                rules: [
                  { required: formData.orgBasicInfo.channel == false?true:false, whitespace: true, message: '请输入供应商编码', },
                ],
              })(<Input
                placeholder={'请输入供应商编码'} disabled={formData.orgBasicInfo.channel == false}
                onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.fmsVendorNum') }}
              />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col className="col" span={8}>
            <FormItem {...formItemLayout}
              label="统一社会信用代码">
              {getFieldDecorator('orgBasicInfo.orgCode', {
                initialValue: formData.orgBasicInfo.orgCode,
                rules: [
                  { required: true, message: '请输入统一社会信用代码', },
                ],
              })(<Input disabled={formData.orgBasicInfo.channel == false}
                placeholder={'请输入统一社会信用代码'}
                onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.orgCode') }}
              />)}
            </FormItem>
          </Col>
          <Col className="col" span={16}>

            <FormItem {...formItemLayout01}
              label="中介公司地址">
              <InputGroup compact>
                <Col span={9}>
                  <FormItem>
                    {getFieldDecorator('orgBasicInfo.addressCodes', {
                      initialValue: formData.orgBasicInfo.addressCodes,
                      rules: [
                        // {required: true, message: '请输入中介公司地址',},
                      ],
                      validator: function (rule, value, callback) {
                        if (!formData.orgBasicInfo.detailAddress) {
                          callback('请输入详细地址')
                        } else {
                          callback()
                        }
                      }
                    })(<Cascader disabled={false} options={allAreaList}
                      onChange={(value, selectedOptions) => inputChange(value, 'orgBasicInfo.addressCodes')}
                      placeholder="请选择省市区" />)}
                  </FormItem>
                </Col>

                <Col span={12}>
                  <FormItem>
                    {getFieldDecorator('orgBasicInfo.detailAddress', {
                      initialValue: formData.orgBasicInfo.detailAddress,
                      rules: [
                        // {required: true,whitespace: true,  message: '请输入详细地址',},
                      ],
                    })(
                      <Input

                        placeholder={'请输入详细地址'}
                        onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.detailAddress') }}
                      />
                    )}
                  </FormItem>
                </Col>

              </InputGroup>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={16}>
            <FormItem {...formItemLayout01}
              label="备注">
              {getFieldDecorator('orgBasicInfo.description', {
                initialValue: formData.orgBasicInfo.description,
                rules: [
                  { required: false, whitespace: true, message: '', },
                ],
              })(<Input
                placeholder={''}
                width={300}
                onChange={(e) => { inputChange(e.target.value, 'orgBasicInfo.description') }}
                style={{ width: 500 }}
              />)}
            </FormItem>
          </Col>
          
        </Row>
      </CollapsiblePanels>


      <CollapsiblePanels title="合作项目" hideUpDownBtn={true} >
        <div className="clearfix mgb1">
          <div className={cx('fr')}>
            <Button type='primary' disabled={false} onClick={() => { updateModal() }}>选择楼盘</Button>
            <Button type='primary' className='mgl1' disabled={isEmpty(selectedRowKeys)} onClick={(e) => {
              e.stopPropagation();
              updateTimeModal()
              // if(!isEmpty(selectedKeys)){
              //   updateTimeModal()
              // }else{
              //   message.info('至少选中一条数据')
              // }
            }}>批量设置楼盘合同有效期</Button>
            <Popconfirm placement="top" title={"确定删除选中项吗？"} onConfirm={() => deleteItems()} okText="确定" cancelText="取消">
              <Button type='primary' className='mgl1' disabled={isEmpty(selectedRowKeys)} >批量删除</Button>
            </Popconfirm>
          </div>
        </div>
        <div className={cx('mt1', 'table_projectList')}>
          <Form>
            <Grid {...gridProps} />
          </Form>
        </div>
      </CollapsiblePanels>

      {/*添加楼盘弹窗*/}
      <PopUpSelect
        tableColumn={[columns[0]]}
        selectedColumn={[columns[0]]}
        queryList={modalObj.queryList}
        selectedTableScroll={{ x: 420 }}
        visible={modalObj.visible}
        refreshByEnter={true}
        closeCbk={e => updateModal()}
        confirmCbk={(onItem) => {
          confirmCbk(onItem)
          console.log(onItem)
        }}
        onChange={(onItem) => {
          // set(tableData,'dataSource',onItem)
          changeState({ onItem: onItem })
        }}
        // handleParam={(params)=>{
        //   return {...params,shelfStatus:1}
        // }}
        isSave={true}
        // isSingle={false}
        onItem={onItem || []}
        defaultReqParams={{ shelfStatus: 1 }}
        requestUrl='admin/estate/adminList?shelfStatus=1'
        method={'POST'}
        title='添加楼盘'
        respListKey='rows'
        idKey='productId'
      // layout={[{span:12},{span:12}]}
      // slot={}
      />


      <Modal
        title={'设置楼盘时间'}
        width='80%'
        // className="pubBiz_CommonModel"
        visible={timeModalObj.visible}
        onCancel={() => { updateTimeModal() }}
        onOk={() => { updateTimeModal(true) }}
      // onOk={}
      >
        <Row>
          <Form className="public_listMain">
            <Row>
              <Col span={12}>
                <FormItem label={'批量设置合同有效期'} {...{
                  labelCol: { span: 6 },
                  wrapperCol: { span: 15 },
                }}>
                  {
                    getFieldDecorator('newTime', {
                      rules: [
                        // { required: true, type: 'array', message: `请选择时间` },
                      ],
                      initialValue: formData.newTime || null
                    })
                      (<RangePicker style={{ width: '100%' }}
                        placeholder={['开始时间', '结束时间']}
                        allowClear={false}
                        format="YYYY-MM-DD"
                        onChange={(dates, dateStrings) => {
                          formData.newTime = dateStrings;
                          changeState({ formData })
                        }} />)
                  }
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Row>

      </Modal>
      <Modal
        title='提示'
        visible={callModal}
        onCancel={() => { updateCallModal(false) }}
        onOk={() => { updateCallModal(false, 1) }}
      >
        <p>{callModalTitle}</p>
        <p>是否要继续提交？</p>
      </Modal>
      {/* 搜索中介公司名称弹窗 */}
      <Modal
        title={'中介公司档案'}
        width='1000px'
        visible={nameModalObj.visible}
        onCancel={() => { onSearchDialog() }}
        onOk={() => { confirmSearchDialog() }}
       
      >
        <div>
            <ListPage pageProps={pageProps}/>
        </div>
      </Modal>
      {/* 搜索团队弹窗 */}
      <Modal
        title={'团队明细'}
        width='800px'
        visible={teamsModalObj.visible}
        onCancel={() => { upTeams() }}
        destroyOnClose={true}
        footer={null}
      >
        <div>
          <Table rowSelection={teamsRowSelection} columns={teamsColumns} dataSource={formData.teams} />
          <div style={{textAlign: 'right',marginTop:'6px'}}>
              <Button type='primary'  style={{marginRight:'10px'}} onClick={() => {confirmTeams()}}>确认</Button>
              <Button onClick={() => {upTeams() }}>取消</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
